package com.scpii.universal.pns.service;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.scpii.universal.dto.UserInfoDto;
import com.scpii.universal.pns.dao.UsersDao;
import com.scpii.universal.pns.entity.Users;

@Service
public class UsersServiceImpl extends PnsBaseServiceImpl<Users, Long> implements
		UsersService {
	@Resource
	public void setBaseDao(UsersDao usersDao) {
		super.setBaseDao(usersDao);
	}

	@Override
	public void saveUsersFromExcel(List<String> contents, UserInfoDto user) {
		int dataSize = contents.size();
		int poolSize = 1;
		if (dataSize > 2000)
			poolSize = 2;
		ExecutorService pool = Executors.newFixedThreadPool(poolSize);
		int taskNum = 0;
		if (dataSize % 2000 == 0)
			taskNum = dataSize / 2000;
		else
			taskNum = dataSize / 2000 + 1;

		for (int i = 1; i <= taskNum; i++) {
			TaskHandler t = new TaskHandler(contents, user, this);
			t.setBeginIndex((i - 1) * 2000 + 1);
			t.setEndIndex(i * 2000);
			pool.execute(t);
		}
		pool.shutdown();
	}

	private class TaskHandler extends Thread {
		private List<String> datas;
		private UserInfoDto user;
		private UsersService usersService;
		private int beginIndex;
		private int endIndex;

		public TaskHandler(List<String> datas, UserInfoDto user,
				UsersService usersService) {
			this.datas = datas;
			this.user = user;
			this.usersService = usersService;
		}

		@Override
		public void run() {
			usersService.saveUsersBatch(datas, user, beginIndex, endIndex);
		}

		public void setBeginIndex(int beginIndex) {
			this.beginIndex = beginIndex;
		}

		public void setEndIndex(int endIndex) {
			this.endIndex = endIndex;
		}

	}

	@Override
	public void saveUsersBatch(List<String> contents, UserInfoDto user,
			int begin, int end) {
		for (int i = begin; i <= end; i++) {

		}
	}
}
